package com.sskj.mine.ui.activity;

import android.support.design.widget.BottomSheetDialog;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.sskj.common.base.App;
import com.sskj.common.base.GlideApp;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.DisposUtil;
import com.sskj.common.util.ImageUtil;
import com.sskj.common.util.SPUtil;
import com.sskj.common.util.ToastUtil;
import com.sskj.lib.RConfig;
import com.sskj.lib.SPConfig;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.CopyUtil;
import com.sskj.mine.R;
import com.sskj.mine.R2;
import com.sskj.mine.bean.MineGoogleBean;
import com.sskj.mine.component.DaggerUserDataComponent;
import com.sskj.mine.presenter.MineChromeVerficationPresenter;

import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import butterknife.BindView;
import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subscribers.DisposableSubscriber;

@Route(path = RConfig.MINE_CHROME_VERIFICATION)//谷歌认证
public class MineChromeVerficationActivity extends BaseActivity<MineChromeVerficationPresenter> {

    @BindView(R2.id.chrome_ewm)
    ImageView chromeEwm;
    @BindView(R2.id.chrome_num)
    TextView chromeNum;
    @BindView(R2.id.chrome_copy)
    TextView chromeCopy;
    @BindView(R2.id.btSubmit)
    Button btSubmit;
    private TextView tvCode;
    private EditText etCode;
    @Inject
    UserViewModel userViewModel;
    private UserData userData;
    DisposableSubscriber disposableSubscriber;
    private MineGoogleBean mineGoogleBean;

    @Override
    protected int getLayoutResId() {
        return R.layout.mine_activity_chrome_verfication;
    }

    @Override
    public MineChromeVerficationPresenter getPresenter() {
        return new MineChromeVerficationPresenter();
    }

    @Override
    protected void initView() {
        super.initView();
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userViewModel.update();
            }
        });
        ClickUtil.click(btSubmit, () -> {
            showBottomDialog();
        });
        setTitle("绑定谷歌验证器");
        ClickUtil.click(chromeCopy, () -> {
            if (TextUtils.isEmpty(chromeNum.getText().toString())) {
                return;
            }
            CopyUtil.copy(chromeNum.getText().toString());
        });
    }

    @Override
    public boolean getImmersion() {
        return false;
    }

    @Override
    protected void initData() {
        mPresenter.bindGoogle(SPUtil.get(SPConfig.ID, ""));
    }

    private void showBottomDialog() {
        BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(mActivity);
        View inflate = LayoutInflater.from(mActivity).inflate(R.layout.mine_bottom_dialog_chrome, null);
        EditText chromeNum = inflate.findViewById(R.id.chrome_num);
        etCode = inflate.findViewById(R.id.chrome_tel_code);
        tvCode = inflate.findViewById(R.id.chrome_send_code);
        ClickUtil.click(tvCode, () -> {
            tvCode.setEnabled(false);
            mPresenter.sendCode(userData.getTel());
        });
        Button btSubmit = inflate.findViewById(R.id.btSubmit);

        ClickUtil.click(btSubmit, () -> {
            String etCodeString = etCode.getText().toString();
            String chromeNumString = chromeNum.getText().toString();
            if (TextUtils.isEmpty(chromeNumString)) {
                ToastUtil.showShort("请输入谷歌验证码");
                return;
            }
            if (TextUtils.isEmpty(etCodeString)) {
                ToastUtil.showShort("请输入短信验证码");
                return;
            }
            mPresenter.bindChrome(mineGoogleBean.getQrcode(), mineGoogleBean.getSecret(), chromeNumString, SPUtil.get(SPConfig.ID, ""), etCodeString);
        });
        bottomSheetDialog.setContentView(inflate);
        bottomSheetDialog.getWindow().findViewById(R.id.design_bottom_sheet)
                .setBackgroundResource(android.R.color.transparent);
        if (mineGoogleBean != null) {
            bottomSheetDialog.show();
        } else {
            ToastUtil.showShort("页面加载有误，请重新进入页面");
        }
    }

    public void sendCodeOk() {
        startCount();
    }

    public void sendCodeError() {
        tvCode.setEnabled(true);
    }

    /**
     * 获取验证码倒计时
     */
    public void startCount() {
        DisposUtil.close(disposableSubscriber);
        disposableSubscriber = new DisposableSubscriber<Long>() {
            @Override
            public void onNext(Long aLong) {
                int time = (int) (60 - aLong);
                tvCode.setText(String.format(App.INSTANCE.getString(R.string.mineRegisterActivity8), time));
            }

            @Override
            public void onError(Throwable t) {
                System.out.println(t.toString());
            }

            @Override
            public void onComplete() {
                tvCode.setText(App.INSTANCE.getString(R.string.mineRegisterActivity9));
                tvCode.setEnabled(true);
                if (!disposableSubscriber.isDisposed()) {
                    disposableSubscriber.dispose();
                    disposableSubscriber = null;
                }

            }
        };
        Flowable.interval(0, 1, TimeUnit.SECONDS, Schedulers.newThread())
                .take(60)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(disposableSubscriber);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        DisposUtil.close(disposableSubscriber);
    }

    public void updateUi(MineGoogleBean mineGoogleBean) {
        this.mineGoogleBean = mineGoogleBean;
        ImageUtil.setImage(mineGoogleBean.getQrcode(), chromeEwm);
        chromeNum.setText(mineGoogleBean.getSecret());
    }

    public void updateUi() {
        userViewModel.update();
    }


}
